package com.example.aftersales.service.impl;

import com.example.aftersales.service.ServiceTicketService;
import com.example.aftersales.utils.Result;
import com.example.aftersales.entity.Ticket;
import com.example.aftersales.mapper.TicketMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
public class ServiceTicketServiceImpl implements ServiceTicketService {

    private final TicketMapper serviceTicketMapper;

    public ServiceTicketServiceImpl(TicketMapper serviceTicketMapper) {
        this.serviceTicketMapper = serviceTicketMapper;
    }

    @Override
    public Result<List<Ticket>> getAllTickets() {
        List<Ticket> tickets = serviceTicketMapper.findAll();
        return Result.success("获取工单列表成功", tickets);
    }

    @Override
    public Result<List<Ticket>> getUserTickets(String userId) {
        List<Ticket> tickets = serviceTicketMapper.findByUserId(userId);
        return Result.success("获取用户工单列表成功", tickets);
    }

    @Override
    public Result<Ticket> getTicketById(Long id) {
        Optional<Ticket> ticketOptional = serviceTicketMapper.findById(id);
        if (ticketOptional.isPresent()) {
            return Result.success("获取工单成功", ticketOptional.get());
        } else {
            return Result.error("未找到该工单");
        }
    }

    @Override
    public Result<String> submitTicket(Ticket ticket) {
        ticket.setSubmitDate(LocalDate.now());
        ticket.setStatus("待处理");
        ticket.getProgress().add("已提交");

        int result = serviceTicketMapper.insert(ticket);
        if (result > 0) {
            return Result.success("售后单提交成功！");
        } else {
            return Result.error("售后单提交失败，请稍后再试！");
        }
    }

    @Override
    public Result<String> updateTicketStatus(Long ticketId, String newStatus, String newProgressStep) {
        Optional<Ticket> ticketOptional = serviceTicketMapper.findById(ticketId);
        if (ticketOptional.isEmpty()) {
            return Result.error("未找到该工单！");
        }

        Ticket ticket = ticketOptional.get();
        ticket.setStatus(newStatus);

        if (newProgressStep != null && !newProgressStep.isEmpty()) {
            ticket.getProgress().add(newProgressStep);
        }

        int result = serviceTicketMapper.updateStatusAndProgress(ticket);
        if (result > 0) {
            return Result.success("工单状态更新成功！");
        } else {
            return Result.error("工单状态更新失败，请稍后再试！");
        }
    }
}